Skip to content

Compiler-Solution for First set, Follow set and LL(1) Parsing table

Solution for First Set

To compute FIRST(X) for all grammar symbols X, apply the following rules until no more terminals or ε can be added to any FIRST set.

  1. If X is a terminal, then FIRST(X)={X}.

  2. If X is a nonterminal and XY1Y2...Yk is a production for some k1, then place ϵ in FIRST(X) if for some i, ϵ is in FIRST(Yi), and ϵ is in all of FIRST(Y1),,FIRST(Yi1). If ϵ is in FIRST(Yi) for all i=1,2,...,k, then add ϵ to FIRST(X). For example, everything in FIRST(Yi) is surely in FIRST(X). If Yi does not derive ϵ, then we add nothing more to FIRST(X), but if Yiϵ, then we add FIRST(Yi+1), and so on.

  3. If Xϵ is a production, then add ϵ to FIRST(X).

Now, we can compute FIRST for any string X+1X2Xnas follows. Add to FIRST(X1X2Xn) all non-ϵ symbols of FIRST(X1). Also add the non-ϵ symbols of FIRST(X2), if ϵ is in FIRST(X1); the non-ϵ symbols of FIRST(X3), if ϵ is in FIRST(X1) and FIRST(X2); and so on. Finally, add ϵ to FIRST(X1X2Xn) if, for all i, ϵ is in FIRST(Xi).

Solution for Follow Set

To compute FOLLOW(A) for all nonterminals A, apply the following rules until nothing can be added to any FOLLOW set:

  1. Place $ in FOLLOW(S), where S is the start symbol, and $ is the input right end marker.

  2. If there is a production AαBβ, then everything in FIRST(β) except ϵ is in FOLLOW(B).

  3. If there is a production AαB, or a production AαBβ, where FIRST(β) contains ϵ, then everything in FOLLOW(A) is in FOLLOW(B).


  1. 对于文法的开始符号S,置 $ 于Follow(S)中;
  2. AαBβ是一个产生式,则把First(β)/{ε}加入到Follow(B)
  3. AαB是一个产生式,或AαBβ是一个产生式且βϵ ,则把Follow(A)加入到Follow(B)

α可以是终结符或者非终结符(包括ϵ),β可以是终结符或者非终结符)

Solution for LL(1) Parsing Table

Suppose the parsing table M is n×m, where n is the number of nonterminals and m is the number of terminals. The table is initialized to be empty.

The entry M[A,α] is a production rule that parser will apply when the current nonterminal is A and the next input symbol is α.

For each production Aα in the (left factored, non-left recursive) grammar, do the following:

  1. Foe each token α in FIRST(α), add the grammar production Aα to M[A,α].
  2. If ϵ is in FIRST(α) then, for each token b in the FOLLOW(A), add Aα to M[A,b].
  3. All other entries in the table are left blank and correspond to a syntax error.

流程:

遍历两次 Production Rule

第一次遍历,对每个 Production Rule 检查 Rule-1

  • 如果 α 是终结符,则把 Aα 加入到 M[A,α]
  • 如果 α 是非终结符,则把 Aα 加入到M[A,b]bFIRST(α)

第二次遍历,对每个 Production Rule 检查 Rule-2

查看Production Rule 中所有可以产生 ϵ 的非终结符 对这些非终结符把 Aϵ 加入到 M[A,b]bFOLLOW(A)